package com.itlong.cloud.commons.service.impl;

import cn.hutool.extra.spring.SpringUtil;
import com.itlong.cloud.POJO.PO.DeviceEntranceInfoPO;
import com.itlong.cloud.POJO.PO.DeviceOnlineStatusAlterLogPO;
import com.itlong.cloud.POJO.VO.Task.TaskProjectInfoVo;
import com.itlong.cloud.POJO.VO.common.DeviceOnlineVO;
import com.itlong.cloud.POJO.VO.property.CloudControllerVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.commons.dao.ICommonsDao;
import com.itlong.cloud.commons.dao.IDeviceEntranceInfoDao;
import com.itlong.cloud.commons.dao.IJDServiceDao;
import com.itlong.cloud.commons.dao.IProjectInfoDao;
import com.itlong.cloud.commons.service.ICloudDeviceOnlineService;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.iot.huawei.util.HuawTokenClient;
import com.itlong.cloud.iot.service.server.AliIotServerService;
import com.itlong.cloud.commons.dao.ICommonsDao;
import com.itlong.cloud.commons.service.ICloudDeviceOnlineService;
import com.itlong.cloud.iottp.IIotDeviceOnlineServiceClient;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.network.https.HttpsPost;
import com.itlong.cloud.utils.node.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <desc>
 * 设备在线接口实现类
 * </desc>
 *
 * @createDate 2019/07/03
 */
@Service
@RefreshScope
public class CloudDeviceOnlineServiceImpl implements ICloudDeviceOnlineService {
    private static final Logger LOG = LoggerFactory.getLogger(CloudDeviceOnlineServiceImpl.class);

    @Value("${" + PlatformConstants.IOT_SMART_CARD_PRODUCT_KEY + "}")
    private String smartCardIotProductKey; //一卡通产品KEY

    @Autowired
    ICommonsDao iCommonsDao;

    @Autowired
    AliIotServerService aliIotServerService;

    @Autowired
    IDeviceEntranceInfoDao iDeviceEntranceInfoDao;

    @Autowired
    IJDServiceDao ijdServiceDao;

    @Autowired
    IProjectInfoDao iProjectInfoDao;

    @Autowired
    HuawTokenClient huawTokenClient;

    @Value("${" + PlatformConstants.HUAWEI_PROJECT_ID + "}")
    private String projectId;

    @Autowired
    RedisService redisService;

    @Autowired
    private IIotDeviceOnlineServiceClient iIotDeviceOnlineServiceClient;

    /**
     * <desc>
     * 维护在线设备缓存
     * <desc/>
     *
     * @return
     * @author Qiang.S
     * @createDate 2019/07/03
     */
    @Override
    public void timeTaskMaintenanceOnline() {
        CloudDeviceOnlineServiceImpl that = SpringUtil.getBean(CloudDeviceOnlineServiceImpl.class);
        that.timeTaskMaintenanceOnline1();
        that.timeTaskMaintenanceOnline2();
        that.timeTaskMaintenanceOnline3();
        that.timeTaskMaintenanceOnline4();
        that.timeTaskMaintenanceOnline5();
        that.timeTaskMaintenanceOnline6();
        //that.timeTaskMaintenanceOnline7();
        that.timeTaskMaintenanceOnline8();
    }

    /**
     * 将原来的timeTaskMaintenanceOnline拆分成多个
     */
    @Async
    public void timeTaskMaintenanceOnline1() {
        List<CloudControllerVO> listIntercom = iCommonsDao.getAllIntercom();
        //云对讲
        if (listIntercom.size() > 0) {
            aliIotServerService.batchGetDeviceStateForOnline(listIntercom.get(0).getIotProductKey(), listIntercom, "1");
        }
    }

    /**
     * 将原来的timeTaskMaintenanceOnline拆分成多个
     */
    @Async
    public void timeTaskMaintenanceOnline2() {
        List<CloudControllerVO> listElevator = iCommonsDao.getAllElevator();
        //云电梯
        if (listElevator.size() > 0) {
            aliIotServerService.batchGetDeviceStateForOnline(listElevator.get(0).getIotProductKey(), listElevator, "2");
        }
    }

    /**
     * 将原来的timeTaskMaintenanceOnline拆分成多个
     */
    @Async
    public void timeTaskMaintenanceOnline3() {
        List<CloudControllerVO> listEntrance = iCommonsDao.getAllEntrance();
        //云门禁
        if (listEntrance.size() > 0) {
            aliIotServerService.batchGetDeviceStateForOnline(listEntrance.get(0).getIotProductKey(), listEntrance, "3");
        }
    }

    /**
     * 将原来的timeTaskMaintenanceOnline拆分成多个
     */
    @Async
    public void timeTaskMaintenanceOnline4() {
        List<CloudControllerVO> listController = iCommonsDao.getAllController();
        //群控器
        if (listController.size() > 0) {
            aliIotServerService.batchGetDeviceStateForOnline(listController.get(0).getIotProductKey(), listController, "4");
        }
    }

    /**
     * 将原来的timeTaskMaintenanceOnline拆分成多个
     */
    @Async
    public void timeTaskMaintenanceOnline5() {
        List<CloudControllerVO> listCluster = iCommonsDao.getAllCluster();
        //联动器
        if (listCluster.size() > 0) {
            aliIotServerService.batchGetDeviceStateForOnline(listCluster.get(0).getIotProductKey(), listCluster, "5");
        }
    }

    /**
     * 将原来的timeTaskMaintenanceOnline拆分成多个
     */
    @Async
    public void timeTaskMaintenanceOnline6() {
        List<CloudControllerVO> listPad = iCommonsDao.getAllPad();
        //平板
        if (listPad.size() > 0) {
            aliIotServerService.batchGetDeviceStateForOnline(listPad.get(0).getIotProductKey(), listPad, "6");
        }
    }

    /**
     * 将原来的timeTaskMaintenanceOnline拆分成多个
     */
    @Async
    public void timeTaskMaintenanceOnline7() {
        List<CloudControllerVO> listSmartCard = iCommonsDao.getAllSmartCard();
        //一卡通
        if (listSmartCard.size() > 0) {
            aliIotServerService.batchGetDeviceStateForOnline(smartCardIotProductKey, listSmartCard, "7");
        }
    }

    /**
     * 将原来的timeTaskMaintenanceOnline拆分成多个
     */
    @Async
    public void timeTaskMaintenanceOnline8() {
        List<CloudControllerVO> listUnibodyFace = iCommonsDao.getUnibodyFace();
        //一体式人脸识别门禁
        if (listUnibodyFace.size() > 0) {
            aliIotServerService.batchGetDeviceStateForOnline(listUnibodyFace.get(0).getIotProductKey(), listUnibodyFace, "8");
        }
    }

    /**
     * <desc>
     * 维护在线设备缓存
     * <desc/>
     *
     * @return
     * @author Qiang.S
     * @createDate 2019/07/03
     */
    @Override
    public List<DeviceEntranceInfoPO> getAllDoorByDeviceUnique(String deviceUnique) {
        return iDeviceEntranceInfoDao.getAllDoorByDeviceUnique(deviceUnique);
    }

    /**
     * <desc>
     * 维护在线设备缓存
     * <desc/>
     *
     * @return
     * @author Qiang.S
     * @createDate 2019/07/03
     */
    @Override
    public List<DeviceEntranceInfoPO> getDoorByGroup(String deviceUnique) {
        return iDeviceEntranceInfoDao.getDoorByGroup(deviceUnique);
    }

    /**
     * <desc>
     * 获取京东设备id
     * </desc>
     *
     * @param deviceUnique
     * @param deviceType
     * @return
     * @author Jiaqi.X
     * @createDate 2020/08/11
     */
    public String getJdDeviceId(String deviceUnique, Integer deviceType) {
        return ijdServiceDao.getJdDeviceId(deviceUnique, deviceType);
    }

    /**
     * <desc>
     * 维护在线设备缓存
     * <desc/>
     *
     * @return
     * @author caoshuai
     * @createDate 2020/09/25
     */
    @Override
    public void timeTaskHWMaintenanceOnline() {
        CloudDeviceOnlineServiceImpl that = SpringUtil.getBean(CloudDeviceOnlineServiceImpl.class);
        that.timeTaskHWMaintenanceOnlineWrap();
    }

    @Async
    public void timeTaskHWMaintenanceOnlineWrap() {
        //获取华为iot项目相关信息
        List<TaskProjectInfoVo> taskProjectInfoVos = iProjectInfoDao.getHWIotProjectInfo();
        if (taskProjectInfoVos == null || taskProjectInfoVos.size() <= 0) {
            return;
        }

        Set<String> projectIds = taskProjectInfoVos.stream().map(TaskProjectInfoVo::getProjectId).collect(Collectors.toSet());

        //查询所有云电梯
        List<CloudControllerVO> listElevator = iCommonsDao.getHWIotAllElevator(projectIds);
        //查询所有云门禁
        List<CloudControllerVO> listEntrance = iCommonsDao.getHWIotAllEntrance(projectIds);
        //查询所有群控器
        List<CloudControllerVO> listController = iCommonsDao.getHWIotAllController(projectIds);
        //查询所有联动器
//        List<CloudControllerVO> listCluster = iCommonsDao.getHWIotAllCluster(projectIds);

        ArrayList<CloudControllerVO> cloudControllerVOS = new ArrayList<>();
        cloudControllerVOS.addAll(listElevator);
        cloudControllerVOS.addAll(listEntrance);
        cloudControllerVOS.addAll(listController);

        try {
            for(CloudControllerVO cloudControllerVO : cloudControllerVOS){

                String result = HttpsPost.doGet(huawTokenClient.getAccessToken(), "https://iotdm.cn-north-4.myhuaweicloud.com/v5/iot/" + projectId + "/devices/" + cloudControllerVO.getHuaweiIotId(), null);
                Map<String, Object> resultMap = JsonUtil.toObject(result, HashMap.class);
                if(resultMap.get("error_code") != null){
                    redisService.del(RedisConstant.HUAWEI_ACCESS_TOKEN_REDIS_KEY);
                    result = HttpsPost.doGet(huawTokenClient.getAccessToken(), "https://iotdm.cn-north-4.myhuaweicloud.com/v5/iot/" + projectId + "/devices/" + cloudControllerVO.getHuaweiIotId(), null);
                    resultMap = JsonUtil.toObject(result, HashMap.class);

                }
                LOG.info("【查询华为云iot设备信息返回结果】"+JsonUtil.toJSON(resultMap));
                if(resultMap.get("status") == null){
                    continue;
                }
                String online = resultMap.get("status").toString();
                DeviceOnlineVO vo = new DeviceOnlineVO(cloudControllerVO.getDeviceUnique(), DateUtil.addCurrentTime(new Date(), 120000), online);
                //设置设备的在线离线状态
                LOG.info("=====维护在线设备缓存======>{}",vo);
                redisService.set(RedisConstant.REDIS_IOT_CLOUD_DEVICE_ONLINE_STATE_CACHE + cloudControllerVO.getDeviceUnique(),
                        RedisConstant.REDIS_IOT_CLOUD_DEVICE_ONLINE_STATE_CACHE_TIME, vo);

                if("ONLINE".equals(vo.getStatus())){
                    if ("1".equals( cloudControllerVO.getDeviceUnique().substring(8,9))) {//云电梯
                        redisService.set(RedisConstant.DEVICE_ELEVATOR_IS_ONLINE_KEY+ cloudControllerVO.getDeviceUnique(),"1");
                    }else if ("5".equals( cloudControllerVO.getDeviceUnique().substring(8,9))) {//群控器
                        redisService.set(RedisConstant.DEVICE_CLUSTER_IS_ONLINE_KEY+cloudControllerVO.getDeviceUnique(),"1");
                    }else if ("2".equals( cloudControllerVO.getDeviceUnique().substring(8,9))) {//云门禁,联动器
                        List<DeviceEntranceInfoPO> list = iIotDeviceOnlineServiceClient.getAllDoorByDeviceUnique( cloudControllerVO.getDeviceUnique());
                        if (list.size() == 0) {
                            list = iIotDeviceOnlineServiceClient.getDoorByGroup( cloudControllerVO.getDeviceUnique());
                        }
                        for (DeviceEntranceInfoPO po : list) {
                            if (po.getEntranceCategory() ==22) {//门禁
                                redisService.set(RedisConstant.DEVICE_ENTRANCE_IS_ONLINE_KEY+po.getDeviceUnique(),"1");
                            }else if (po.getEntranceCategory() ==23) {//联动器
                                redisService.set(RedisConstant.DEVICE_WIPPEN_IS_ONLINE_KEY+po.getDeviceUnique(),"1");
                            }else if (po.getEntranceCategory() ==24) {//一体式人脸识别门禁
                                redisService.set(RedisConstant.DEVICE_UNIBODY_FACE_IS_ONLINE_KEY+po.getDeviceUnique(),"1");
                            }
                        }
                    }
                }else if ("OFFLINE".equals(vo.getStatus())){

                    if ("1".equals(cloudControllerVO.getDeviceUnique().substring(8,9))) {//云电梯,联动器
                        redisService.del(RedisConstant.DEVICE_ELEVATOR_IS_ONLINE_KEY+cloudControllerVO.getDeviceUnique());
                    }else if ("5".equals(cloudControllerVO.getDeviceUnique().substring(8,9))) {//群控器
                        redisService.del(RedisConstant.DEVICE_CLUSTER_IS_ONLINE_KEY+cloudControllerVO.getDeviceUnique());
                    }else if ("2".equals(cloudControllerVO.getDeviceUnique().substring(8,9))) {//云门禁
                        List<DeviceEntranceInfoPO> list = iIotDeviceOnlineServiceClient.getAllDoorByDeviceUnique(cloudControllerVO.getDeviceUnique());
                        if (list.size() == 0) {
                            list = iIotDeviceOnlineServiceClient.getDoorByGroup(cloudControllerVO.getDeviceUnique());
                        }
                        for (DeviceEntranceInfoPO po : list) {
                            if (po.getEntranceCategory() ==22) {//门禁
                                redisService.del(RedisConstant.DEVICE_ENTRANCE_IS_ONLINE_KEY+po.getDeviceUnique());
                            }else if (po.getEntranceCategory() ==23) {//联动器
                                redisService.del(RedisConstant.DEVICE_WIPPEN_IS_ONLINE_KEY+po.getDeviceUnique());
                            }else if (po.getEntranceCategory() ==24) {//一体式人脸识别门禁
                                redisService.del(RedisConstant.DEVICE_UNIBODY_FACE_IS_ONLINE_KEY+po.getDeviceUnique());
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            LOG.error("【查询华为云iot设备信息返回结果】"+ e.getMessage());
        }
    }

}
